package com.xbongbong.pro.message.thread;

import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.enums.PackageTypeEnum;
import com.xbongbong.pro.message.enums.PushTypeEnum;
import com.xbongbong.pro.message.pojo.dto.MessageRabbitMqDTO;
import com.xbongbong.pro.message.service.MessageService;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.sys.domain.entity.CompanyEntity;
import com.xbongbong.sys.domain.entity.FeeCompanyEntity;
import com.xbongbong.sys.enums.RoleEnum;
import com.xbongbong.sys.model.CompanyModel;
import com.xbongbong.sys.model.FeeCompanyModel;
import com.xbongbong.sys.model.UserModel;
import lombok.Getter;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Setter
@Getter
public class ExpiredReminderThread extends Thread {

    private static final Logger LOG = LoggerFactory.getLogger(ExpiredReminderThread.class);
    private CompanyModel companyModel;
    private FeeCompanyModel feeCompanyModel;
    private UserModel userModel;
    private MessageService messageService;
    private Integer start;
    private Integer pageSize;

    public ExpiredReminderThread(Integer start , Integer pageSize) {
        this.start = start;
        this.pageSize = pageSize;
    }


    @Override
    public void run() {

        Integer pageNum = 100;
        Map<String,Object> param = new HashMap<>();
        param.put("del", 0);
        //企业授权状态 -1：解除授权 0：禁用 1：正常 2：待激活
        param.put("status", 1);
        //到期提醒推送给所有公司的管理员，不考虑推送是否开启
//		param.put("isPushMessage", 1);
        //来源，1:钉钉 2:独立版
        param.put("source", 1);
        Integer end = this.start + this.pageSize;
        for(;this.start<=end;this.start=this.start+pageNum){
            param.put("start", this.start);
            param.put("pageNum", pageNum);
            List<CompanyEntity> companys = companyModel.findEntitys(param);
            for(CompanyEntity company : companys){
                //存在客户的才进入计算,先根据corpid计算客户数
                try {
                    expiredReminderPush(company);
                } catch (Exception e) {
                    // TODO: handle exception
                    LOG.error("到期提醒异常，corpid:"+company.getCorpid(), e);
                }
            }
        }
    }

    private void expiredReminderPush(CompanyEntity company) throws Exception{
        Long monthDay = 30L;
        Long halfMonthDay = 15L;
        Long sevenDay = 7L;
        Long threeDay = 3L;
        Long oneDay = 1L;
        Long expiryDay = 0L;

        String corpid = company.getCorpid();
        String corpName = company.getCorpName();
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("del", 0);
        param.put("feeTypeIn", Arrays.asList(PackageTypeEnum.ADVANCED.getType(), PackageTypeEnum.ULTIMATE.getType()));
        param.put("orderByStr", "start_time,end_time asc");
        // TODO: company
        List<FeeCompanyEntity> list = feeCompanyModel.findEntitys(param);
        //套餐开始时间
        Long startTime = 0L;
        //套餐结束时间
        Long endTime = 0L;
        int today = DateUtil.getTodayInt();

        // 刚刚过期的套餐
        // 当前的套餐
        FeeCompanyEntity feeNow = null;
        // 即将生效的套餐(下一个已付费套餐)
        FeeCompanyEntity feeAfter = null;
        for (FeeCompanyEntity entity : list) {
            Long startTimeM = DateTimeUtil.getTodayInt(entity.getStartTime());
            Long endTimeM = DateTimeUtil.getTodayInt(entity.getEndTime());
            Integer isActiveM = entity.getIsActive();
            Integer isPay = entity.getIsPay();
            if (isPay == 0 && isActiveM == 1
                    && today >= startTimeM && today <= endTimeM + 86400) {
                // 暂时只对高级版和旗舰版试用套餐进行遍历，即将到期前，进行钉钉消息推送
                endTime = endTimeM;
                feeNow = entity;
            }
//            if (isPay == 1 && today < startTimeM) {
//                feeAfter = entity;
//            }
        }

        String endTimeStr = DateTimeUtil.getString(endTime*1000L, DateUtil.SDFDate);

        //剩余时间
        Long leftTime = (endTime - today)/86400 + 1;

        String showMsg = "";
        if (null != feeNow) {

            //判断下一个套餐是否已经付费，若付费则不提醒
            if(null != feeAfter){
                Integer isPayAfter = feeAfter.getIsPay();
                if(isPayAfter.equals(1)){
                    return ;
                }
            }
            Integer isPayNow = feeNow.getIsPay();
            String title = I18nMessageUtil.getMessage(I18nStringConstant.XBB_CRM_EXPIRE_REMIND);
            if(isPayNow.equals(0)){
                //免费用户
                Integer feeType = feeNow.getFeeType();
                String featureMessage = I18nMessageUtil.getMessage(StringConstant.ADVANCED_FEATURE_MESSAGE);
                String packageMessage = I18nMessageUtil.getMessage(StringConstant.ADVANCED_PACKAGE_MESSAGE);
                if (Objects.equals(PackageTypeEnum.ULTIMATE.getType(), feeType)) {
                    featureMessage = I18nMessageUtil.getMessage(StringConstant.ULTIMATE_FEATURE_MESSAGE);
                    packageMessage = I18nMessageUtil.getMessage(StringConstant.ULTIMATE_PACKAGE_MESSAGE);
                }
                String feeName = PackageTypeEnum.getByType(feeNow.getFeeType()).getName();
                if(threeDay.equals(leftTime)){
                    title = String.format(I18nMessageUtil.getMessage(I18nStringConstant.XBB_TRIAL_WILL_EXPIRE_REMIND), feeName);
                    showMsg = String.format(I18nMessageUtil.getMessage(StringConstant.MESSAGE_PRO_FREE_EXPIRED_REMINDER), corpName, feeName, 3, endTimeStr, packageMessage, featureMessage);
                }
                if(expiryDay.equals(leftTime)){
                    // 到期提醒
                    title = String.format(I18nMessageUtil.getMessage(I18nStringConstant.XBB_TRIAL_EXPIRE_REMIND), feeName);
                    showMsg = String.format(I18nMessageUtil.getMessage(StringConstant.MESSAGE_PRO_FREE_EXPIRED), corpName, feeName, endTimeStr, packageMessage);
                }
            }else{
                //付费用户
                if(monthDay.equals(leftTime)){
                    showMsg = String.format(I18nMessageUtil.getMessage(StringConstant.MESSAGE_VIP_EXPIRED_REMINDER), corpName, 30, endTimeStr, StringConstant.SUPPORT_HOTLINE);
                }
                if(halfMonthDay.equals(leftTime)){
                    showMsg = String.format(I18nMessageUtil.getMessage(StringConstant.MESSAGE_VIP_EXPIRED_REMINDER), corpName, 15, endTimeStr, StringConstant.SUPPORT_HOTLINE);
                }
                if(sevenDay.equals(leftTime)){
                    showMsg = String.format(I18nMessageUtil.getMessage(StringConstant.MESSAGE_VIP_EXPIRED_REMINDER), corpName, 7, endTimeStr, StringConstant.SUPPORT_HOTLINE);
                }
                if(threeDay.equals(leftTime)){
                    showMsg = String.format(I18nMessageUtil.getMessage(StringConstant.MESSAGE_VIP_EXPIRED_REMINDER), corpName, 3, endTimeStr, StringConstant.SUPPORT_HOTLINE);
                }
                if(oneDay.equals(leftTime)){
                    showMsg = String.format(I18nMessageUtil.getMessage(StringConstant.MESSAGE_VIP_EXPIRED_REMINDER), corpName, 1, endTimeStr, StringConstant.SUPPORT_HOTLINE);
                }
                if(expiryDay.equals(leftTime)){
                    showMsg = String.format(I18nMessageUtil.getMessage(StringConstant.MESSAGE_VIP_EXPIRED), corpName, "", StringConstant.SUPPORT_HOTLINE);
                }
            }

            if(!StringUtil.isEmpty(showMsg)){
                List<Integer> roleIdList = Arrays.asList(RoleEnum.ADMIN.getCode(), RoleEnum.BOSS.getCode());
                List<String> userIds = userModel.getUserIdsByRoles(corpid, roleIdList);
                Long pushTime = DateTimeUtil.getTodayInt() + 11*3600;
                PushTypeEnum pushTypeEnum = PushTypeEnum.EXPIRED_PUSH;
                MessageRabbitMqDTO messageRabbitMqDTO = new MessageRabbitMqDTO(corpid, userIds, Collections.singletonList(0L), 0, pushTime,
                        title, showMsg, null, null);
                messageService.insertPushData(messageRabbitMqDTO, pushTypeEnum);
                LOG.info("发送消息给公司corpid="+ corpid +"，消息内容为：" + showMsg);
            }
        }
    }
}
